package com.oe.vdi.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class JniBitmapView extends View {

    private static final String LOG_TAG = "OEView";

    public JniBitmapView(Context context) {
        super(context);
    }

    public JniBitmapView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public JniBitmapView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private Handler handler = new Handler();
    private Runnable myRunnable = new Runnable() {
        public void run() {
            updateGraphics(bitmap);
            postInvalidate();
        }
    };

    long start_time = -1;
    int fps_count = 0;
    Paint fpsPaint = null;
    private void drawFPS(Canvas canvas) {
        if (fpsPaint == null) {
            fpsPaint = new Paint();
            fpsPaint.setColor(Color.GREEN);
            fpsPaint.setStyle(Paint.Style.FILL);
            fpsPaint.setTextSize(48);
        }

        if (start_time <= 0) {
            start_time = System.currentTimeMillis();
        } else {
            long timeDif = (System.currentTimeMillis() - start_time);
            double fps = fps_count * 1000.0d / timeDif;
            canvas.drawText(String.format("%2.2f fps", fps), 50, 50, fpsPaint);
            if (timeDif >= 10000) {
                fps_count = 0;
                start_time = System.currentTimeMillis();
            }
        }
        fps_count++;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, 0, 0, null);
        drawFPS(canvas);
        handler.post(myRunnable);
    }

    private Bitmap bitmap;
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // TODO Auto-generated method stub
        super.onSizeChanged(w, h, oldw, oldh);
        Log.d("mDebug", "onSizeChanged,w=" + w + ",h=" + h + ",oldw=" + oldw + ",oldh=" + oldh);

        bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    }

    static {
        System.loadLibrary("oe_egl");
    }

    public native void updateGraphics(Bitmap bmp);
}
